# python标准库 logging
import logging

def f1_default():
    # 什么都不配置的情况下，logging为默认root logger，logging默认是warn级别，warn以下级别不会打印
    # 默认输出流到控制台sys.stderr
    logging.warning(f'hello world {logging}')


log_filename = 'demo.log'
def f2_log2file():
    # 配置日志打印到文件，filemode默认是a追加(filemode取值与open函数mode取值相同，w为每次重新创建)， 
    # logging.INFO为int类型
    # logging一般需要在开始时初始化，上面第一次调用logging.warning时会初始化默认handler
    # 默认handler初始化完毕后通过basicConfig配置将不会生效，除非执行force参数重新初始化handler
    # 本句初始化配置代码应该放在import后的第一行，此处演示force=True强制重新初始化
    logging.basicConfig(filename=log_filename, filemode='w', level=logging.DEBUG, force=True)

    # 20 -> info
    print('log level -> ',getattr(logging, 'info'.upper()), logging.getLevelName(20))

    logging.debug('This message should go to the log file')
    logging.info('So should this')
    logging.warning('And this, too')
    logging.error(Exception('oops error'))
    logging.critical('critical error info')
    logging.log(20, 'this equals info() method') # log指定打印机别 此处指定info级别相当于info方法
    logging.exception(Exception('error with stack info')) # 与error不同点就是可以打印堆栈信息

    logging.info('%s this is %s format log', 'look', 'simple')
    logging.info(f'str format {log_filename}')
    logging.info('str format {}'.format(log_filename))
    logging.info('str format %s' % log_filename)

def f3_log_format():
     # 日志格式配置
    log_format = '%(asctime)s %(threadName)s-%(thread)d %(levelname)s: %(message)s'
    # 时间格式datefmt
    logging.basicConfig(filename=log_filename, filemode='w', format=log_format
        # , datefmt='%Y/%m/%d %I:%M:%S %p' # 12小时 AM/PM 模式
        , datefmt='%Y/%m/%d %H:%M:%S' # 24小时 模式
        , level=logging.DEBUG, force=True)
    logging.info('this is formated message.')

    # 获取自定义名称的logger
    log = logging.getLogger('myLogger')
    log.info('hello world')


def cls():
    # 读取日志文件打印到控制台
    print('+' * 66)
    logfile = open(log_filename)
    print(logfile.read())
    logfile.close()

    # 删除日志文件
    import os
    # 删除前必须先关闭日志文件占用
    logging.shutdown() # flush close
    os.remove(log_filename)

if __name__ == '__main__':
    # f1_default()
    # f2_log2file()
    f3_log_format()

    cls()